﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace DIM_Update
{
    public partial class Index : Form
    {
        private JObject Net { get; set; }
        private JObject Load1 { get; set; }
        public Index()
        {
            InitializeComponent();
        }
        private void Index_Load(object sender, EventArgs e)
        {
            try
            {
                Load1 = (JObject)JsonConvert.DeserializeObject(File.ReadAllText("update.json"));
                Net = (JObject)JsonConvert.DeserializeObject(HttpGet(Load1["Url"].ToString()));
                label2.Text = Load1["Edition"].ToString();
                richTextBox1.Text = Net["Notice"].ToString();
                if (label2.Text == Net["Edition"].ToString())
                {
                    button1.Text = "已经是最新版";
                    button1.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "程序提示");
            }
        }
        /// <summary>
        /// 发送get请求的方法
        /// </summary>
        private static string HttpGet(string Url, string postDataStr = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "application/json";
            request.ProtocolVersion = HttpVersion.Version11;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }
        /// <summary>
        /// 下载实时返回下载进度
        /// </summary>
        /// <param name="URL">下载地址</param>
        /// <param name="filename">本地存储地址</param>
        /// <param name="action">委托回调函数</param>
        public static void DownloadFileData(string URL, string filename, Action<int, int> action)
        {
            float percent = 0;
            try
            {
                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength, totalDownloadedByte = 0;
                System.IO.Stream st = myrp.GetResponseStream(), so =
                new System.IO.FileStream(filename, System.IO.FileMode.Create);
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    so.Write(by, 0, osize);
                    osize = st.Read(by, 0, (int)by.Length);
                    percent = (float)totalDownloadedByte / (float)totalBytes * 100;//当前位置
                    ///反馈回调 返回下载进度
                    action((int)totalBytes, (int)percent);
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            progressBar1.Maximum = Net.Count - 2;
            for (int i = 0; i < Net.Count - 2; i++)
            {
                progressBar1.Maximum = 100;
                string filestr = Net["Url" + i.ToString()].ToString();
                string[] filename_path = filestr.Split(new char[] { '#' });
                DownloadFileData(filename_path[0], filename_path[1], delegate (int a, int b)
                {
                    progressBar1.Value = b;
                });
                progressBar1.Value = i;
            }
            progressBar1.Value++;
            MessageBox.Show("更新完成", "温馨提示");
            this.Dispose();
            this.Close();
        }
    }
}
